/*
 * @Author: wfl
 * @LastEditors: wfl
 * @description: 
 * @updateInfo: 本次更新内容：
 * @Date: 2021-03-18 16:36:23
 * @LastEditTime: 2021-04-29 12:02:57
 */
import { Injectable } from '@nestjs/common';
import { resolve } from 'path';
import { existsSync, mkdirs, move, Stats, readdir, createWriteStream, rmdirSync } from 'fs-extra'
import { IncomingForm } from 'formidable';
const fs = require('fs');
import config from '../config'

interface FileStatus {
    isFileExist: boolean;
    name: string;
}

@Injectable()
export class UploadService {

    getFileChunk(): string {
        return 'getFileChunk'
    }

    // 上传切片
    async uploadChunk(body, files): Promise<object> {
        const { name, fileHash, fileMd5No } = body;
        // 创建以该文件MD5为文件名的目录
        const chunkFolder = resolve(config.chunkFolderUrl, <string>fileHash);
        if (!existsSync(chunkFolder)) {
            await mkdirs(chunkFolder);
        }
        // 创建写入流 - 文件名为切片的MD5 - fileMd5No
        let ws = fs.createWriteStream(`${chunkFolder}/${fileMd5No}`);
        // 写入流
        ws.write(files[0].buffer)
        // 存放切片的位置
        return {
            code: 1,
            msg: 'upload success'
        }
    }

    // 合并切片
    async merageChuank(fileMd5: string): Promise<string> {
        // 根据MD5确定是哪个文件，获取文件路径
        const fileUrl = resolve(config.chunkFolderUrl, <string>fileMd5);
        console.log('fileUrl', fileUrl);
        // 读取路径下的所有切片
        const chunkList = await readdir(fileUrl)
        chunkList.sort((a,b) => parseInt(a.split('-')[1]) - parseInt(b.split('-')[1]))
        console.log('chunkList', chunkList);
        const size = config.chunkSize;
        await Promise.all(
            chunkList.map((chunk, index) => {
                
            })
        )
        return 'filepath'
    }

    // 根据文件md5获取已上传文件切片
    async getReadyChunk(fileMd5: string): Promise<object>{
        const chunkFolder = resolve(config.chunkFolderUrl);
        const folder = fs.readdirSync(chunkFolder);
        let loadedList = [];
        if(folder){
            let index = folder.findIndex((name) => name === fileMd5);
            if(index !== -1){
                let chunks = fs.readdirSync(`${chunkFolder}/${fileMd5}`)
                console.log(chunks)
                loadedList = chunks
            }
        }
        // 没有目录则返回undefined       
        return {
            code: 1,
            msg: '获取已上传切片成功',
            data: loadedList
        }
    }
}